package com.alibaba.datax.common.util;

import java.math.BigInteger;

/**
 * @Description
 * @Author yintongkai
 * @Date 2022/4/27 下午4:36
 **/
public class G36Util {
    /**
     * 0-9 a-z 36 位, 可以理解为 36 进制
     */
    private final static char[] numberSystem= new char[]{
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b','c','d','e','f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    };
    private final static BigInteger base = new BigInteger("36");

    /**
     * 获取当前 36 进制 数的索引
     * 即 一个字符时: 36 进制的 十进制表示
     * @param c
     * @return
     */
    private static BigInteger getNumberSystemIndex(String c) {
        int index = 0;
        for (int i = 0; i < numberSystem.length; i++) {
            String s = String.valueOf(numberSystem[i]);
            if (c.equals(s)) {
                index = i;
                break;
            }
        }
        return new BigInteger(String.valueOf(index));
    }


    /**
     * 自定义进制数转BigInteger
     * @param s
     * @return
     */
    public static BigInteger string2BigInteger(String s) {
        if (null == s) {
            throw new IllegalArgumentException("参数 字符串 不能为空.");
        }
        BigInteger result = BigInteger.ZERO;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            int pow = chars.length - i - 1;
            BigInteger index = getNumberSystemIndex(String.valueOf(chars[i]));
            result = result.add(index.multiply(base.pow(pow)));
        }
        return result;
    }

    /**
     * BigInter转成自定义进制数
     * @param n
     * @return
     */
    public static String bigInteger2String(BigInteger n) {
        if (null == n) {
            throw new IllegalArgumentException("参数 bigInteger 不能为空.");
        }
        String s = "";
        if (n.compareTo(BigInteger.ZERO) == 0) {
            s = "0";
        }
        while (n.compareTo(BigInteger.ZERO) != 0) {
            BigInteger mod = n.mod(base);
            char c = numberSystem[mod.intValue()];
            s = c + s;
            n = n.divide(base);
        }
        return s;
    }
}
